<template>
  <el-col :span="24">
    <el-card class="card">
      <h3>谣言列表</h3>
      <el-collapse v-model="activeNames" class="rumors">
        <div @click="handleClick(item.rumorType-1)" v-for="(item, index) in rumors" :key="index" style="width:100%">
          <el-collapse-item ref="collapseItem" :name="index">
            <template slot="title">
              <span class="title">{{item.title}}</span>
              <i class="header-icon el-icon-view mr5"></i>
              <span>阅读量 {{item.score}}</span>
            </template>
            <div class="mf20">
              <h4>{{item.mainSummary}}</h4>
              <p>{{item.body}}</p>
            </div>
          </el-collapse-item>
        </div>
      </el-collapse>
    </el-card>
  </el-col>
</template>

<script>
import { axiosUtil } from '../network/axiosUtil.js'
export default {
  name: 'Rumor',
  data () {
    return {
      imgHeight: '0',
      rumors: [],
      activeNames: []
    }
  },
  methods: {
    getRumors () {
      axiosUtil({
        url: '/News/getRumors',
        method: 'get'
      }).then(data => {
        if (data) {
          //代表请求数据成功
          this.rumors = data
        }
      })
    },
    handleClick (rumorType) {
      if (this.$refs.collapseItem[rumorType].isActive) {
        console.log(this.rumors[rumorType].score);
        this.rumors[rumorType].score++
      }
    },
    updateScore () {
      axiosUtil({
        url: '/News/updateRumorScore',
        method: 'post',
        data: {
          rumors: this.rumors
        }
      }).then(data => {
        if (data) {
          //代表请求数据成功
          this.rumors = data
        }
      })
    }
  },
  mounted () {
    this.getRumors()
    window.addEventListener("beforeunload", this.updateScore)
  },
  // 在组件被<keep-alive></keep-alive>包裹时，组件不会被销毁，destroyed生命周期函数不会执行，而是会缓存下来，组件来回却换时调用activated 和 deactivated 这两个生命周期钩子函数
  deactivated () {
    this.updateScore()
    window.removeEventListener("beforeunload", this.updateScore)
  }
}
</script>

<style scoped>
.rumors {
  margin: 0px 20px;
  border: none;
}

.rumors >>> .el-collapse-item__header .title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 5px;
}

.rumors >>> .el-collapse-item__header {
  margin: 10px 0px;
}

.rumors >>> .el-collapse-item__content {
  font-size: 14px;
}

.el-icon-view {
  position: relative;
  top: 1px;
}
</style>